<template>
  <div class="cart-content">
    <div class="cart-header">
      <div>
        <span>购物车</span>
        <span class="cart-manager" @click="mamageCar">{{ isEdit ? "完成" : "管理" }}</span>
      </div>

      <span class="good-num">共{{ goods.length }}件宝贝</span>

    </div>
    <van-list
      :value="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <cart-items @onItemCheckChange="onItemCheckChange"
                  @onItemCountChange="onItemCountChange"
                  :image="emptyImage"
                  :list="goods" @itemClick="openDetail" @changeSku="changeSku"/>

    </van-list>
    <div class="submit-bar">
      <div class="submit-bar-content">
        <van-checkbox v-model="checkedAll" @change="changeCheckAll">全选</van-checkbox>
        <div class="submit-bar-price" v-if="!isEdit">
          <span class="submit-bar-text">合计:</span>
          <span>¥
            <span class="submit-bar-price-integer">{{ checkedGoodsAmount.toString().split('.')[0] }}</span>
            {{ checkedGoodsAmount.toString().split('.')[1] }}
          </span>
        </div>
        <van-button v-if="!isEdit" class="submit-button van-submit-bar__button van-submit-bar__button--danger "
                    type="danger" round
                    @click="checkOrder"
                    color="linear-gradient(to right,#ff6034,#ee0a24)">提交订单
        </van-button>

        <van-button v-if="isEdit" class="submit-button van-submit-bar__button van-submit-bar__button--danger "
                    type="danger" round
                    color="linear-gradient(to right,#ff6034,#ee0a24)" @click="deleteGoods">删除{{ delGoods.length }}
        </van-button>
      </div>

    </div>
    <van-sku
      v-model="showSku"
      :sku="sku"
      :goods="products"
      :goods-id="goodsId"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
    >
      <template #sku-actions="props">
        <div class="van-sku-actions">
          <van-button
            square
            size="large"
            type="danger"
            @click="props.skuEventBus.$emit('sku:buy')"
          >确认
          </van-button>
        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
import CartItems from '../../components/CartItems'
import {cartChecked, cartDelete, cartList, cartUpdate} from '../../api/items'
import {Toast} from 'vant'

export default {
  name: 'index',
  components: {CartItems},
  data () {
    return {
      goods: [],
      isShowList: true,
      loading: false,
      finished: false,
      refreshing: false,
      checkedAll: false,
      emptyImage: '',
      checkedGoodsAmount: 0,
      count: 0,
      isEdit: false,
      checkedGoods: [],
      showSku: false,
      goodsId: 111,
      delGoods: [],
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: '颜色',
            k_id: '1',
            v: [
              {
                id: '30349',
                name: '天蓝色',
                imgUrl:
                  'https://img.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg',
                previewImgUrl: 'https://img.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg'
              },
              {
                id: '1215',
                name: '白色',
                imgUrl:
                  'https://img.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg',
                previewImgUrl: 'https://img.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg'
              }
            ],
            largeImageMode: true, //  是否展示大图模式
            k_s: 's1'
          },
          {
            k: '尺寸',
            k_id: '2',
            v: [
              {
                id: '1193',
                name: '1'
              },
              {
                id: '1194',
                name: '2'
              }
            ],
            k_s: 's2'
          }
        ],
        // 所有 sku 的组合列表，如下是：白色1、白色2、天蓝色1、天蓝色2
        list: [
          {
            id: 2259,
            price: 120, // 价格
            discount: 122,
            s1: '1215',
            s2: '1193',
            s3: '0',
            s4: '0',
            s5: '0',
            stock_num: 20, // 库存
            goods_id: 946755
          },

          {
            id: 2257,
            price: 130,
            discount: 132,
            s1: '30349',
            s2: '1193',
            s3: '0',
            s4: '0',
            s5: '0',
            stock_num: 40, // 库存
            goods_id: 946755
          },
          {
            id: 2258,
            price: 100,
            discount: 100,
            s1: '30349',
            s2: '1194',
            s3: '0',
            s4: '0',
            s5: '0',
            stock_num: 50, // 库存
            goods_id: 946755
          }
        ],
        price: '5.00',
        stock_num: 227, // 商品总库存
        none_sku: false, // 是否无规格商品
        hide_stock: false // 是否隐藏剩余库存
      },
      products: {
        // 商品标题
        title: '',
        // 默认商品 sku 缩略图
        picture: ''
      },
      checkedGoodsCount: 0
    }
  },

  methods: {
    deleteGoods () {
      cartDelete(this.delGoods).then(res => {
        this.handleResult(res)
      })
    },
    mamageCar () {
      this.isEdit = !this.isEdit
    },
    onItemCountChange (item) {
      cartUpdate({
        number: item.number,
        goodsId: item.goodsId,
        id: item.id,
        productId: item.productId
      })
    },
    onItemCheckChange (item) {
      if (!this.isEdit) {
        this.handleCheck()
      } else {
        this.handleDelete(item)
      }
    },
    handleDelete (item) {
      if (item.checked) {
        this.delGoods.push(item.productId)
      } else {
        let start = this.delGoods.indexOf(item.productId)
        if (start >= 0) {
          this.delGoods.splice(start, 1)
        }
      }
    },
    handleCheck (item) {
      this.requestCheck([item.productId], item.checked)
    },
    handleResult (res) {
      let data = res.data.data
      this.goods = data.cartList
      if (this.goods == null || this.goods.length <= 0) {
        this.emptyImage = require('../../assets/images/is_empty.png')
      }
      this.checkedGoodsAmount = data.cartTotal.checkedGoodsAmount
      this.checkedGoodsCount = data.cartTotal.checkedGoodsCount
      let goodsCount = data.cartTotal.goodsCount
      if (goodsCount !== 0 && goodsCount === this.checkedGoodsCount) {
        this.checkedAll = true
      }
    },
    checkOrder () {
      if (this.checkedGoodsCount > 0) {
        this.$router.push({name: 'confirm'})
      } else {
        Toast('您还没有选择宝贝哦！')
      }
    },
    changeSku () {
      this.showSku = true
    },
    onBuyClicked (skuData) {
      console.log(skuData)
    },
    openDetail (item) {
      this.$router.push({
        path: '/product/detail'
      })
    },

    changeCheckAll (status) {
      let checkeStatus = 0
      let productIds = []
      if (status) {
        checkeStatus = 1
      }
      this.goods.forEach(item => {
        productIds.push(item.productId)
      })
      this.requestCheck(productIds, checkeStatus)

      this.goods.forEach(item => {
        item.checked = status
      })
    },
    requestCheck (productIds, checked) {
      if (!this.isEdit) {
        cartChecked({productIds: productIds, isChecked: checked})
          .then(res => {
            this.handleResult(res)
          }).catch((reason) => {
            this.emptyImage = 'error'
          })
      }
    },
    onSubmit () {

    },
    onLoad () {
      cartList().then(res => {
        this.handleResult(res)
      })
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.count++

      this.onLoad()
    }
  }
}
</script>

<style scoped>
.cart-content {
  height: 100%;
  background-color: #f2f2f2;
}

.cart-manager {
  font-size: 16px;
  font-weight: normal;
  float: right;
}

.good-num {
  margin: 10px 0;
  color: gray;
  font-size: 14px;

}

.cart-header {
  padding: 10px;
  font-size: 20px;
  font-weight: bold;
  color: black;
}

.submit-bar {
  background-color: white;
  position: fixed;
  bottom: 50px;
  left: 0;
  z-index: 100;
  width: 100%;
}

.submit-bar-text {
  font-size: 14px;
  color: #323233;
}

.submit-bar-price {
  margin-right: 10px;
  flex: 1;
  text-align: right;
  color: #ee0a24;
  font-weight: 500;
  font-size: 14px;
}

.submit-bar-price-integer {
  font-weight: bold;
  font-size: 20px;
}

.submit-bar-content {
  align-items: center;
  padding: 5px 16px;
  display: flex;
  justify-content: space-between;
}
</style>
